<?php
/**
 * Created by PhpStorm.
 * User: lzhy@lzhy.me
 * Date: 2019/4/12 0012
 * Time: 16:56
 */
namespace app\admin\event;

use think\Db;

class Utils
{
    /**
     * ifr提交响应
     * @param $res
     * @param bool $debug
     */
    public static function ifrResponse($res,$debug = false)
    {
        if($debug){
            print_r([
                'get' => $_GET,
                'post' => $_POST,
                'response' => $res
            ]);
        }
        if(empty($res)){
            $res = ['success'=>0,'msg'=>'位置错误'];
        }

        exit('<script>parent.ifrSubmitResponseHandle('.json_encode($res).')</script>');
    }

    /**
     * 生成树形
     * @param $list
     * @param int $rootId
     * @param int $level
     * @return array
     */
    public static function arr2tree($list, $rootId = 0, $level = 1)
    {
        $tree = [];
        foreach($list as $leaf) {
            if($leaf['pid'] == $rootId) {
                $leaf['level'] = $level;
                foreach($list as $sub) {
                    if($sub['pid'] == $leaf['id']) {
                        $leaf['children'] = self::arr2tree($list, $leaf['id'],$level+1);
                        break;
                    }
                }

                $tree[] = $leaf;
            }
        }

        return $tree;
    }

    /**
     * 单行数据删除
     * @param $table
     * @param $val
     * @param string $key
     * @param bool $soft
     */
    public static function rowDel($table,$val,$key = 'id',$soft = false)
    {
        $res = ['success'=>0,'msg'=>'系统错误'];
        if($table && $val){
            $res = ['success'=>0,'msg'=>'删除失败，请稍后再试'];
            if($soft){
                if(Db::table($table)->where($key,$val)->update(['is_delete'=>1])){
                    $res = ['success'=>1,'msg'=>'删除成功'];
                }
            }else{
                if(Db::table($table)->where($key,$val)->delete()){
                    $res = ['success'=>1,'msg'=>'删除成功'];
                }
            }
        }

        exit(json_encode($res));
    }
}